<template>
  <div class="addVideo" style="width: 100%">
    <a-divider>海报信息</a-divider>
    <div class="clearfix">
      <a-upload
        :action="$api.upload"
        :data="postData"
        :multiple="true"
        name="file"
        accept="image/*"
        listType="picture-card"
        :fileList="fileList"
        :showUploadList="format()"
        @preview="handlePreview"
        @change="handleChange"
        :remove="removePic"
        :customRequest="upload"
      >
        <div v-if="fileList.length < 9 && optType === 2">
          <a-icon type="plus" />
          <div class="ant-upload-text">上传项目海报</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
      <br />
    </div>
    <p>*海报推荐尺寸（ 335px * 193px ），不强制</p>
    <a-divider>视频信息</a-divider>
    <a-button
      v-if="optType === 2"
      type="primary"
      style="margin-bottom: 20px"
      @click="showModal"
      :disabled="!$commonJs.isAth('addVideoList')"
    >
      <a-icon type="plus" />
      新增
    </a-button>
    <c-table
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      style="width: 100%"
      @changeOpt="changeOpt"
    >
    </c-table>
    <a-modal
      title="新增视频"
      v-model="visible"
      @ok="addHandleSubmit"
      @cancel="addHandleCancel"
    >
      <a-form :form="form">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  { required: true, message: '请输入名称！' },
                  {
                    validator: $validate.validateLength,
                    max: 50,
                    min: 1
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item
          label="视频文件"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <a-upload
            v-decorator="[
              'upload',
              {
                initialValue: initInfo.upload,
                valuePropName: 'fileList',
                getValueFromEvent: normFile
              }
            ]"
            name="file"
            accept="video/*"
            :multiple="false"
            :action="$api.upload"
            :data="postData"
            :beforeUpload="beforeUpload"
          >
            <a-button> <a-icon type="upload" /> 上传视频 </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import cTable from "@/components/table/index";
import { Modal } from "ant-design-vue";
import reqwest from "reqwest";
import { getToken } from "@/tool/qiniu";
export default {
  name: "baseInfo",
  components: {
    cTable
  },
  data() {
    this.addHandleSubmit = this.$debounce(this.addHandleSubmit, 800);
    return {
      fileList: [],
      previewVisible: false,
      previewImage: "",
      visible: false,
      form: this.$form.createForm(this),
      headers: {
        authorization: "authorization-text"
      },
      pagination: {},
      columns: [
        {
          title: "ID",
          dataIndex: "id",
          align: "center",
          width: 70
        },
        {
          title: "名称",
          dataIndex: "name",
          width: 350,
          scopedSlots: { customRender: "name" }
        },
        {
          title: "源文件",
          dataIndex: "video",
          scopedSlots: { customRender: "videoSourceLile" }
        },
        {
          title: "发布人/ID",
          dataIndex: "username"
        },
        {
          title: "创建时间",
          dataIndex: "create_time"
        },
        {
          title: "操作",
          dataIndex: "opt",
          width: 110,
          type: "btn",
          list: [
            {
              ath: "delVideoList",
              label: "删除",
              extraValue: "delete",
              className: "text-danger"
            }
          ],
          scopedSlots: { customRender: "opt" }
        }
      ],
      dataSource: [],
      initInfo: {
        upload: []
      },
      loading: false,
      postData: {
        token: ""
      },
      optType: 2
    };
  },
  methods: {
    format() {
      if (this.optType === 2) {
        return true;
      } else {
        return { showPreviewIcon: true, showRemoveIcon: false };
      }
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    removePic(file) {
      this.$ajax
        .post(this.$api.delProjectPicList, {
          id: file.uid,
          type: 2
        })
        .then(() => {
          this.$notification.success({
            message: "删除海报成功"
          });
          return true;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
          return false;
        });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    upload(data) {
      let formData = new FormData();
      formData.append("file", data.file);
      let timestamp2 = new Date().getTime();
      let typeArr = data.file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "poster/" + timestamp2 + "." + type;
      let token = getToken(savekey);
      formData.append("token", token);
      this.saveFile(formData, data);
    },
    saveFile(formData, data) {
      data.onProgress();
      reqwest({
        url: this.$api.upload,
        method: "post",
        processData: false,
        data: formData,
        success: e => {
          data.file.response = e;
          data.onSuccess();
          this.uploadFile(e, data);
        },
        error: () => {
          data.OnError();
        }
      });
    },
    uploadFile(data, info) {
      this.$ajax
        .post(this.$api.addProjectPicList, {
          picture: data.key,
          project_id: this.$route.params.id,
          type: 1
        })
        .then(res => {
          this.$notification.success({
            message: "新增海报成功"
          });
          this.fileList.forEach(item => {
            if (info.file.uid === item.uid) {
              item.uid = res.id;
              return true;
            }
          });
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
    },
    showModal() {
      this.visible = true;
    },
    addHandleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          let obj = JSON.parse(JSON.stringify(values));
          if (values.upload) {
            obj.video = values.upload[0].response.key;
          }
          obj.type = 1;
          obj.project_id = this.$route.params.id;
          delete obj.upload;
          this.$ajax
            .post(this.$api.addVideoList, obj)
            .then(() => {
              this.$notification.success({
                message: "操作成功"
              });
              this.addHandleCancel();
              this.getInfo();
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "video/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
    },
    normFile(e) {
      if (e.fileList.length > 1) {
        e.fileList.splice(0, 1);
      }
      return e && e.fileList;
    },
    addHandleCancel() {
      this.form.resetFields();
      this.visible = false;
    },
    changeOpt(item) {
      this.del(item);
    },
    del(item) {
      let that = this;
      Modal.confirm({
        title: "您确定删除该信息吗？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          that.$ajax
            .post(that.$api.delVideoList, {
              id: item.id,
              type: 2
            })
            .then(() => {
              that.$notification.success({
                message: "删除成功"
              });
              that.getInfo();
            })
            .catch(err => {
              that.$notification.error({
                message: err
              });
            });
        }
      });
    },
    getInfo() {
      this.$ajax
        .get(this.$api.getProjectPicList, {
          project_id: this.$route.params.id
        })
        .then(res => {
          this.fileList = [];
          let fileList = res.data;
          fileList.forEach(item => {
            this.fileList.push({
              uid: item.id,
              status: "done",
              url: this.$api.picPre + item.picture,
              name: item.picture
            });
          });
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
      this.$ajax
        .get(this.$api.getVideoList, {
          project_id: this.$route.params.id,
          page_size: this.pagination.pageSize,
          page: this.pagination.current
        })
        .then(res => {
          this.dataSource = res.data;
          this.pagination.total = res.total_count;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    if (this.$route.name === "editProject") {
      this.optType = 2;
    } else if (this.$route.name === "detailsProject") {
      this.optType = 3;
      this.columns.pop();
    }
    this.getInfo();
  }
};
</script>

<style scoped lang="less">
.components-form-demo-advanced-search {
  align-items: flex-start !important;
}
</style>
